import { getUserList, getUserInfo } from '@/api/subscriber'
import { type SubscriberList, type Subscriber } from '@/models/subscriber'

export async function GetSubscriberInfo(type: string): Promise<Subscriber[]> {
  try {
    const res = await getUserList(type)
    const subscriberList: SubscriberList[] = res.data

    const userInfoPromises: Promise<Subscriber>[] = subscriberList.map(
      async (subscriberListItem: SubscriberList) => {
        const userId = subscriberListItem.id

        try {
          const userInfoResponse = await getUserInfo(userId)
          const userInfo: Subscriber = userInfoResponse.data

          userInfo.gender = userInfo.gender === '1' ? '男' : '女'
          return userInfo
        } catch (error) {
          console.error(`根据id ${userId} 获取用户信息失败:`, error)
          return {} as Subscriber
        }
      }
    )

    const subscriberInfo: Subscriber[] = await Promise.all(userInfoPromises)
    return subscriberInfo
  } catch (error) {
    console.error('用户列表拉取失败:', error)
    return []
  }
}

export async function GetUserList(type: string): Promise<{ id: number; name: string }[]> {
  const res = (await getUserList(type)) as any
  const data = res.data as any[]
  const result: { id: number; name: string }[] = []
  data.forEach((val) => {
    result.push({
      id: val.id,
      name: val.name
    })
  })
  return result
}
